import {Component, ElementRef, OnInit, ViewChild} from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {environment} from '../../../environments/environment';
import {HttpResult, User} from '../../core/http-entity';
import {Store} from '@ngxs/store';
import {Router} from '@angular/router';
import {NzModalService} from 'ng-zorro-antd';
import {VideoAction} from '../../state/video.action';
import {OssPathPipe} from "../../app.pipes";

@Component({
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.less', './home-upload.less']
})
export class HomeComponent implements OnInit {

  user: User;
  isSpinning = false;

  @ViewChild('filesInput')
  filesInputElm: ElementRef;

  hotspots: string[] = [];

  typeTrainCount = {
    KJG: 0,
    YG: 0,
    HW: 0,
    SAR: 0
  }

  imageAllCount = {
    kjg: 0,
    yg: 0,
    hw: 0,
    sar: 0
  }

  pasteText: string;

  constructor(private http: HttpClient, private store: Store, private router: Router, private nzModal: NzModalService,
              private ossPathPipe: OssPathPipe) {
  }

  ngOnInit(): void {
    this.http.get(`${environment.API_URL}/v1/users/0`).subscribe((result: HttpResult<User>) => {
      if (HttpResult.succeed(result.code)) {
        this.user = result.data;
      }
    });

    this.loadHotspot();
    // this.loadTypeTrainCount();
    this.loadAllImageCount();
  }

  fileUpload(evt: any): void {

    const fileList = evt.target.files as FileList;
    const fileCount = fileList.length;

    // 判断文件中是否含有视频
    let videoCount = 0;
    for (let i = 0; i < fileCount; i++) {
      if (fileList[i].type.startsWith('video')) {
        // 含有视频
        videoCount++;
        if (fileCount > 1) {
          // 含有多个视频
          this.nzModal.error({
            nzTitle: '一次只能上传一个视频'
          });
        } else {
          // 只有一个视频，将视频传给第二个页面
          this.store.dispatch(new VideoAction(fileList[i]));

          this.router.navigate(['/detect']);
        }

        return;
      }
    }
    if (videoCount === 0) {
      // 没有视频，走图片逻辑
      if (fileList.length > 500) {
        // 限制一次最多上传500张
        this.nzModal.error({
          nzTitle: '单次最多上传20张'
        });

        this.clearFiles();
        return;
      }
      if (fileList.length > 0) {
        this.onFileDropped(fileList);
      }
    }


  }

  clearFiles(): void {
    this.filesInputElm.nativeElement.value = '';
  }


  onPasteImage(evt: ClipboardEvent): void {

    if (!(evt.clipboardData && evt.clipboardData.items)) {
      // 粘贴板没东西
      return;
    }
    for (let i = 0, len = evt.clipboardData.items.length; i < len; i++) {
      const item = evt.clipboardData.items[i];
      if (item.kind === 'string') {
        // 粘贴网址
        // 这里的item.getAsString是异步的，所以需要用promise来做异步的处理
        const promise = new Promise<string>((resolve, reject) => {
          item.getAsString((url) => {
            // 如果将 this.uploadWithUrl(imageUrl);写到这个里面，将会出现一个bug，这个bug是从detect的组件返回的时候，本组件的ngOnInit方法将不执行
            resolve(url);
          });
        });

        promise.then((imageUrl) => {
          this.uploadWithUrl(imageUrl);
        });
      } else if (item.kind === 'file') {
        const file = item.getAsFile();
        const formData = new FormData();
        formData.append('files', file);
        this.uploadWithFiles(formData);
      }

      // 只循环一次
      break;
    }
  }

  onFileDropped(fileList: FileList): void {
    const fileCount = fileList.length;

    // 判断文件中是否含有视频
    let videoCount = 0;

    for (let i = 0; i < fileCount; i++) {
      if (fileList[i].type.startsWith('video')) {
        // 含有视频
        videoCount++;
        if (fileCount > 1) {
          // 含有多个视频
          this.nzModal.error({
            nzTitle: '一次只能上传一个视频'
          });
        } else {
          // 只有一个视频，将视频传给第二个页面
          this.store.dispatch(new VideoAction(fileList[i]));

          this.router.navigate(['/detect']);
        }

        return;
      }
    }

    if (videoCount === 0) {
      const formData = new FormData();
      for (let i = 0; i < fileCount; i++) {
        formData.append('files', fileList[i]);
      }
      this.uploadWithFiles(formData);

    }


  }

  uploadWithFiles(formData: FormData): void {
    this.isSpinning = true;
    this.http.post(`${environment.API_URL}/v1/detect/files`, formData).subscribe((result: HttpResult<string>) => {
      this.isSpinning = false;
      if (HttpResult.succeed(result.code)) {
        this.router.navigate(['/detect', {detectId: result.data}]);
      } else {
        this.nzModal.error({
          nzTitle: '上传失败',
          nzContent: result.message
        })
      }
    }, () => {
      this.isSpinning = false;
      this.clearFiles();
    });
  }

  uploadWithUrl(url: string): void {
    this.isSpinning = true;
    this.http.post(`${environment.API_URL}/v1/detect/link`, {
      url
    }).subscribe((result: HttpResult<string>) => {
      this.isSpinning = false;
      if (HttpResult.succeed(result.code)) {
        this.router.navigate(['/detect', {detectId: result.data}]);
      } else {
        this.clearFiles();
        this.nzModal.error({
          nzTitle: '图片地址错误'
        });
        this.pasteText = '';
      }
    }, () => {
      this.isSpinning = false;
      this.clearFiles();

      this.nzModal.error({
        nzTitle: '网络错误，请稍后重试'
      });
      this.pasteText = '';
    });
  }

  loadHotspot() {
    this.http.get(`${environment.API_URL}/v1/hotspots`).subscribe((result: HttpResult<string[]>) => {
      if (HttpResult.succeed(result.code)) {
        this.hotspots = result.data;
      }
    });
  }

  detectHotspot(ossKey) {
    this.uploadWithUrl(this.ossPathPipe.transform(ossKey));
  }

  loadTypeTrainCount() {
    this.http.get(`${environment.API_URL}/v1/sample-oss-file/getTypeTrainCount`).subscribe((result: HttpResult<any>) => {
      if (HttpResult.succeed(result.code)) {

        for (let i = 0, len = result.data.length; i < len; i++) {
          if (result.data[i].hasOwnProperty("KJG")) {
            this.typeTrainCount.KJG = result.data[i].KJG;
          } else if (result.data[i].hasOwnProperty("HW")) {
            this.typeTrainCount.HW = result.data[i].HW;
          } else if (result.data[i].hasOwnProperty("YG")) {
            this.typeTrainCount.YG = result.data[i].YG;
          } else if (result.data[i].hasOwnProperty("SAR")) {
            this.typeTrainCount.SAR = result.data[i].SAR;
          }
        }
      }
    });
  }

  loadAllImageCount(): void {
    this.http.get(`${environment.API_URL}/v1/sample-oss-file/getAllImageCount`).subscribe((result: HttpResult<any>) => {
      if (HttpResult.succeed(result.code)) {
        console.log('data', result.data);
        this.imageAllCount = result.data;

      }
    });
  }

}
